package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
import java.time.LocalDateTime;


@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;

    @Scheduled(cron = "0 * * * * ? ") //每分钟执行一次
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}",LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        //select * from orders where status=#{status} and order_time= now()- 15分钟
        List<Orders> timeoutOrders =orderMapper.getTimeOutOrder(Orders.PENDING_PAYMENT,time);

        if(timeoutOrders!=null&&timeoutOrders.size()!=0){
            for (Orders orders:timeoutOrders) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelReason("用户支付超时");
                orders.setCancelTime(LocalDateTime.now());
                orderMapper.update(orders);
            }
        }
    }
    @Scheduled(cron = "0 0 1 * * ? ") //每天凌晨一点执行一次
    public void processTimeoutDeliver(){
        log.info("定时处理派送中订单：{}",LocalDateTime.now());

        //上个工作日即0：00之前派送中的订单
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> timeoutOrders =orderMapper.getTimeOutOrder(Orders.DELIVERY_IN_PROGRESS,time);

        if(timeoutOrders!=null&&timeoutOrders.size()!=0){
            for (Orders orders:timeoutOrders) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }
}
